package com.atguigu.yygh.msm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.ConstantPropertiesUtils;
import com.zhenzi.sms.ZhenziSmsClient;

import lombok.Data;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;



import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class MsmServiceImpl implements MsmService {
	
//	@Autowired
//	private ZhenziSmsClient client;
//	
//	@Bean
//    public ZhenziSmsClient initSMS() {
//        if (client == null) {
//            client = new ZhenziSmsClient(ConstantPropertiesUtils.API_URL, ConstantPropertiesUtils.APP_ID, ConstantPropertiesUtils.APP_SECRECT);
//            return client;
//        }
//        return client;
//    }
	
	//查询榛子云剩余当前账户可发验证码短信条数
//    public Integer checkBalance() throws Exception {
//        String balance = client.balance();   //{"code":0,"data":537}
//        isSendSuccess isSendSuccess = JSONObject.parseObject(balance, isSendSuccess.class);
//        return (int)isSendSuccess.getData();
//    }
    
    //生成验证码和验证码id
//    private Map<String, Object> createVerificationCode() {
//        HashMap<String, Object> map = new HashMap<>();
//        //这个是榛子云短信平台用户中心下的短信管理的短信模板的模板id
//        map.put("templateId", "5812");
//        //生成验证码
//        int pow = (int) Math.pow(10, ConstantPropertiesUtils.CODE_LENGTH - 1);
//        String verificationCode = String.valueOf((int) (Math.random() * 9 * pow + pow));
//        //随机生成messageId，验证验证码的时候，需要携带这个参数去取验证码
//        String messageId = UUID.randomUUID().toString();
//        map.put("messageId", messageId);
//        String[] templateParams = new String[2];
//        //两个参数分别为验证码和过期时间
//        templateParams[0] = verificationCode;
//        templateParams[1] = String.valueOf(ConstantPropertiesUtils.TIME_OUT);
//        map.put("templateParams", templateParams);
//        return map;
//    }
    
   
	 //发送验证码（如果params的success为true，则发送成功，则需要把params中的messageId和验证码存起来，验证验证码的时候用到）
    public boolean send(String phoneNumber,String code) throws Exception {
    	//生成验证码
        Map<String, Object> params = new HashMap<>();
        //发送手机目标（number字段不可修改）
        params.put("number", phoneNumber);
        if (StringUtils.isEmpty(code)){
            params.put("code",code);       
        }
        //这个是榛子云短信平台用户中心下的短信管理的短信模板的模板id
        params.put("templateId", "5816");
        //随机生成messageId，验证验证码的时候，需要携带这个参数去取验证码
        String messageId = UUID.randomUUID().toString();
        params.put("messageId", messageId);
        String[] templateParams = new String[2];
        //两个参数分别为验证码和过期时间
        templateParams[0] = code;
        templateParams[1] = String.valueOf(ConstantPropertiesUtils.TIME_OUT);
        params.put("templateParams", templateParams);
        params.put("createTime",System.currentTimeMillis());
        
        ZhenziSmsClient client = new ZhenziSmsClient(ConstantPropertiesUtils.API_URL, ConstantPropertiesUtils.APP_ID, ConstantPropertiesUtils.APP_SECRECT);
        
	    String result = client.send(params);
	    System.out.println(result);
	    isSendSuccess success = JSONObject.parseObject(result, isSendSuccess.class);
	    if (success.getCode() == 0 ) {
	        params.put("success",true);
	        return true;
	    }else {
	        params.put("success",false);
	        return false;    
	    }
    }
    
    //验证短信验证码,传入缓存中存入的messageId和验证码
    public boolean checkMessage(String messageId, String cacheCode,ZhenziSmsClient client) throws Exception {
    	
        String result = client.findSmsByMessageId(messageId);
        Verification verification = JSONObject.parseObject(result, Verification.class);
        if (verification.getCode() == 0) {
            //取到了数据，开始验证码是否正确
            String veificationCode = verification.getData().getMessage();
            int index = veificationCode.indexOf("验证码:");
            String code = veificationCode.substring(index + 4, index + 4 + ConstantPropertiesUtils.CODE_LENGTH);
            //验证验证码
            if (!code.equals(cacheCode)) {
                return false;
            }
            //验证时间是否过期
            Date createTime = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").parse(verification.getData().getCreateTime());
            long spent = new Date().getTime() - createTime.getTime();
            if (spent / (1000 * 60) > ConstantPropertiesUtils.TIME_OUT) {
                return false;
            }
        } else {
            return false;
        }
        return true;
    }


//    //mq发送短信封装
//    @Override
//    public boolean send(MsmVo msmVo) {
//        if(!StringUtils.isEmpty(msmVo.getPhone())) {
//            boolean isSend = this.send(msmVo.getPhone(), msmVo.getParam());
//            return isSend;
//        }
//        return false;
//    }
//
//    private boolean send(String phone, Map<String,Object> param) {
//        //判断手机号是否为空
//        if(StringUtils.isEmpty(phone)) {
//            return false;
//        }
//        //整合阿里云短信服务
//        //设置相关参数
//        DefaultProfile profile = DefaultProfile.
//                getProfile(ConstantPropertiesUtils.REGION_Id,
//                        ConstantPropertiesUtils.ACCESS_KEY_ID,
//                        ConstantPropertiesUtils.SECRECT);
//        IAcsClient client = new DefaultAcsClient(profile);
//        CommonRequest request = new CommonRequest();
//        //request.setProtocol(ProtocolType.HTTPS);
//        request.setMethod(MethodType.POST);
//        request.setDomain("dysmsapi.aliyuncs.com");
//        request.setVersion("2017-05-25");
//        request.setAction("SendSms");
//
//        //手机号
//        request.putQueryParameter("PhoneNumbers", phone);
//        //签名名称
//        request.putQueryParameter("SignName", "我的谷粒在线教育网站");
//        //模板code
//        request.putQueryParameter("TemplateCode", "SMS_180051135");
//
//        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
//
//        //调用方法进行短信发送
//        try {
//            CommonResponse response = client.getCommonResponse(request);
//            System.out.println(response.getData());
//            return response.getHttpResponse().isSuccess();
//        } catch (ServerException e) {
//            e.printStackTrace();
//        } catch (ClientException e) {
//            e.printStackTrace();
//        }
//        return false;
//    }
    
    @Data
    static class isSendSuccess implements Serializable {
        private Integer code;
        private Object data;
    }
    
  //验证验证码的时候，榛子云返回的报文
    //实例：{"code":0,"data":{"message":"验证码:33356，2分钟内有效，请勿泄漏给他人使用。","appName":"云短信体验","createTime":"2021-03-10 19:24:19","status":"success","toNumber":"15871770252","messageId":"123"}}
    @Data
    static class Verification implements Serializable {
        private Integer code;
        private Message data;
    }
    
    @Data
    static class Message implements Serializable {
        private String message;
        private String appName;
        private String createTime;
        private String status;
        private String toNumber;
        private String messageId;
    }

	

}
